package com.addplus.townmall.server.web.consumer.config.webscoket;

import com.addplus.townmall.server.api.model.authority.User;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptorAdapter;
import org.springframework.messaging.support.MessageHeaderAccessor;

/**
 * 类名: UserInterceptor
 *
 * @author zhangjiehang
 * @version V1.0
 * @date 2017/12/21 下午5:02
 * @description 类描述: 客户端渠道拦截适配器
 */
public class UserInterceptor extends ChannelInterceptorAdapter {

    /**
     * 获取包含在stomp中的用户信息
     */
    @Override
    public Message<?> preSend(Message<?> message, MessageChannel channel) {
        StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
        if (StompCommand.CONNECT.equals(accessor.getCommand())) {
            Object raw = message.getHeaders().get(SimpMessageHeaderAccessor.USER_HEADER);
            if(raw!=null){
                if (raw instanceof User) {
                    User user = (User) raw;
                    Integer userId = user.getId();
//                    user.setName(userId.toString());
                    // 设置当前访问器的认证用户
                    //accessor.setUser(user);
                }
            }
        }
        return message;
    }
}
